new Vue({
    el: '#app',
    data() {
        return {
            fileList: [],
            tableData: [],
            form: {
                page: 1,
                limit: 15,
            },
            loading: false,
            success: 0,
            error: 0,
            Start_Date: '',
            End_Date: '',
            Store_SerialNumber:[],
            store:[],
            Sales_Unit_Price_SerialNumber:'',
        }
    },
    mixins:[importMixin],
    mounted() {
        this.getData();
    },
    methods: {
        getData(){
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: "business_store_info",
                    Condition: "Row_Status='0'"
                },
                success: function (data) {
                    that.store = data;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitUpload(i = 0) {
            if (i < this.tableData.length) {
                if (!this.Start_Date){
                    this.$message({
                        message: '请选择开始时间',
                        type: 'warning'
                    })
                    return
                } else if (this.Store_SerialNumber.length == 0){
                    this.$message({
                        message: '请选择适用店铺',
                        type: 'warning'
                    })
                    return
                }
                if (i==0) {//首次初始化
                    this.success= 0;
                    this.error= 0;
                }
                this.loading = true;
                if (this.tableData[i].isError) {
                    this.tableData[i].isStatus = '2';
                    this.error++;
                    this.submitUpload(i + 1);
                }else if (!this.tableData[i].Supplier_Article_SerialNumber) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '供应商品内码不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (this.tableData[i].Unit_Price == 0) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '销售单价不能为零'
                    this.error++;
                    this.submitUpload(i + 1);
                } else { //校验通过
                    let data = {};
                    if (i == 0) { //首次添加
                        let business_sales_unitprice_storescope = [];
                        this.Store_SerialNumber.forEach(Store_SerialNumber=>{
                            business_sales_unitprice_storescope.push({
                                Sales_Unit_Price_StoreScope_SerialNumber:'',
                                Sales_Unit_Price_SerialNumber:'',
                                Store_SerialNumber
                            })
                        })
                        let obj = {
                            Sales_Unit_Price_SerialNumber: '',
                            Start_Date: this.Start_Date==null?'':this.Start_Date,//开始时间
                            End_Date: this.End_Date==null?'':this.End_Date,//结束时间
                            Enterprise_Info_SerialNumber: '',
                            Children: {
                                business_sales_unitprice_detail: [{
                                    Sales_Unit_Price_Detail_SerialNumber: '',
                                    Sales_Unit_Price_SerialNumber: '',
                                    Supplier_Article_SerialNumber:this.tableData[i].Supplier_Article_SerialNumber,
                                    Unit_Price:this.tableData[i].Unit_Price,
                                    Brand_SerialNumber:this.tableData[i].Brand_SerialNumber
                                }],
                                business_sales_unitprice_storescope,
                            }
                        }
                        data = { Add: { business_sales_unitprice: [obj] } };
                    } else {//后续添加只添加到子表
                        let obj = { 
                            Sales_Unit_Price_Detail_SerialNumber: '',
                            Sales_Unit_Price_SerialNumber: this.Sales_Unit_Price_SerialNumber,
                            Supplier_Article_SerialNumber:this.tableData[i].Supplier_Article_SerialNumber,
                            Unit_Price:this.tableData[i].Unit_Price,
                            Brand_SerialNumber:this.tableData[i].Brand_SerialNumber
                        }
                        data = { Add: { business_sales_unitprice_detail: [obj] } };
                    }
                    this.submitForm({ Data: JSON.stringify(data) }, (res) => {
                        if (res.Status == 'success') {
                            if (i==0) {
                                this.Sales_Unit_Price_SerialNumber = res.Data;
                            }
                            this.tableData[i].isStatus = '1';
                            this.tableData[i].Cause = '',
                            this.success++;
                        } else {
                            this.tableData[i].isStatus = '2';
                            this.tableData[i].Cause = '未知错误'
                            this.error++;
                        }
                        this.submitUpload(i + 1);
                    })
                }
            } else if (i != 0) {
                this.loading = false;
                this.$message.success("批量导入结束")
            } else {
                this.$message({
                    message: '请先导入模板后再上传',
                    type: 'warning'
                })
            }
        },
        submitForm(data, callback) {
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data,
                success: function (res) {
                    callback(res)
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                let Supplier_Article = [];
                let sql1 = "";
                json.forEach((item, index) => {
                    let Supplier_Article_SerialNumber = item['供应商品内码']?item['供应商品内码']:''
                    if (!Supplier_Article.some(i => i == Supplier_Article_SerialNumber)) {
                        Supplier_Article.push(Supplier_Article_SerialNumber);
                        if (index == 0) {
                            sql1 = sql1 + "business_supplier_article.Supplier_Article_SerialNumber='" + Supplier_Article_SerialNumber + "'\r\n"
                        } else {
                            sql1 = sql1 + " or business_supplier_article.Supplier_Article_SerialNumber='" + Supplier_Article_SerialNumber + "'\r\n"
                        }
                    }
                })
                //查询商品信息
                $.ajax({
                    headers: requestHeaders(),
                    type: 'POST',
                    url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                    data: {
                        SQLSerialNumber: 'A_business_supplier_article2',
                        Condition: '',
                        ExtensionCondition: window.btoa(unescape(encodeURIComponent(`and (${sql1})`))),
                    },
                    success: function (Result) {
                        let arr = [];
                        json.forEach(item => {
                            let Supplier_Article_SerialNumber = item['供应商品内码']?item['供应商品内码']:''
                            let Unit_Price = item['销售单价']?item['销售单价']:0
                            if (Result.some(i => i.Supplier_Article_SerialNumber == Supplier_Article_SerialNumber)){
                                arr.push({
                                    ...Result.filter(i => i.Supplier_Article_SerialNumber == Supplier_Article_SerialNumber)[0],
                                    Sales_Unit_Price_Detail_SerialNumber: '',
                                    Sales_Unit_Price_SerialNumber: '',
                                    Supplier_Article_SerialNumber,
                                    Unit_Price,
                                    isEdit: false,
                                    isStatus: '0',
                                    Cause: '',
                                })
                            } else {
                                arr.push({
                                    Sales_Unit_Price_Detail_SerialNumber: '',
                                    Sales_Unit_Price_SerialNumber: '',
                                    Supplier_Article_SerialNumber,
                                    Unit_Price,
                                    isEdit: false,
                                    isError: true,
                                    isStatus: '2',
                                    Cause: '该商品未查到,可能原因:\r\n1.该供应商品内码不正确 \r\n2.该商品未获取到采购价格',
                                })
                            }
                        });
                        that.tableData = arr
                    },
                    complete: function (XMLHttpRequest) {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                })
            }
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleEdit(row) {//修改当前行
            row.isEdit = !row.isEdit
        },
        handleRemove(index) {//移除当前行id
            this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
        },
        handleClean() {//清空
            this.$confirm('是否要清空导入数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = []
            }).catch(() => { });
        },
    },
})